<template>
  <VanField
    class="picker-field"
    :model-value="fieldValue"
    is-link
    readonly
    @click="showPicker = true"
    v-bind="$attrs"
  />
  <VanPopup
    class="picker-field__popup"
    v-model:show="showPicker"
    round
    position="bottom"
  >
    <VanPicker
      :columns="columns"
      :columns-field-names="columnsFieldNames"
      :selected-values="selectedValues"
      @cancel="showPicker = false"
      @confirm="onConfirm"
    ></VanPicker>
  </VanPopup>
</template>

<script setup>
import { ref, computed } from "vue";

const props = defineProps({
  modelValue: String,
  name: String,
  columns: Array,
  columnsFieldNames: Object,
});
const emits = defineEmits("update:modelValue", "update:name");

const showPicker = ref(false);
const fieldValue = computed(() => {
  if (props.columns && props.modelValue) {
    return props.columns.find((item) => item.value === props.modelValue)?.text;
  }
  return "";
});

const selectedValues = computed(() => {
  if (Array.isArray(props.modelValue)) {
    return props.modelValue;
  } else if (props.modelValue) {
    return [props.modelValue];
  }
  return [];
});

const onConfirm = ({ selectedOptions }) => {
  let item = selectedOptions[0];
  emits("update:modelValue", item.value);
  showPicker.value = false;
};
</script>

<style lang="scss" scoped></style>
